<template>
  <scroll-view 
    scroll-y 
    class="video-container"
    :scroll-top="scrollTop"
    @scroll="handleScroll"
	@scrolltolower="loadMoreVideos"
    :scroll-with-animation="true"
  >
    <!-- 视频列表 -->
    <view 
      v-for="(item, index) in videoList" 
      :key="item.id"
      class="video-wrapper"
      :style="{height: windowHeight + 'px'}"
    >
      <video
        :src="item.url"
        :id="'video-'+index"
        :autoplay="index === currentIndex"
        :controls="false"
        :show-center-play-btn="false"
        :enable-progress-gesture="false"
        loop
        class="video-item"
        @play="onVideoPlay(index)"
        @error="onVideoError"
      ></video>
      
      <!-- 视频交互层（点赞/评论等） -->
      <view class="interaction-layer">
        <view class="right-bar">
          <view class="action-btn" @click="showComment(item)">
            <u-icon name="grid-fill" color="#fff" size="28"></u-icon>
            <text>{{ item.commentCount }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 加载更多提示 -->
    <view v-if="loading" class="loading-more">
      <u-loading mode="circle"></u-loading>
    </view>
	<u-popup :show="showPopup" mode="bottom">
	        <view class="flex justify-center align-baseline">
	            <u-number-box v-model="page2" @change="pageChange"></u-number-box>
				<u-button size="small" @click="jumpPage" type="primary" text="确定"></u-button>
				<u-button size="small" @click="copyAddress" type="danger" text="复制"></u-button>
				<u-button size="small" @click="showPopup = false" type="danger" text="关闭"></u-button>
			</view>
		</u-popup>
  </scroll-view>
</template>
<script>
export default {
  data() {
	  let page = uni.getStorageSync("page");
	  page = page ? page : 1;
    return {
      videoList: [],          // 视频数据列表
      currentIndex: 0,        // 当前播放索引
      scrollTop: 0,           // 滚动位置
      windowHeight: 0,        // 窗口高度
      loading: false,         // 加载状态
      isScrolling: false,     // 滚动锁定
      videoContexts: {},      // 视频实例集合
      page: page,                // 当前页码
      pageSize: 5,             // 每页数量
	  showPopup: false,
	  page2: page
    }
  },
  onLoad() {
    this.initSystemInfo();
    this.loadVideos();
  },
  onReachBottom() {
    this.loadMoreVideos();
  },
  methods: {
    // 初始化系统信息
    initSystemInfo() {
      uni.getSystemInfo({
        success: (res) => {
          this.windowHeight = res.windowHeight;
        }
      });
    },
    
    // 加载视频数据
    async loadVideos() {
      if (this.loading) return;
      this.loading = true;
      
      try {
        const res = await uni.request({
          url: 'http://185.150.138.156:81/videos',
          method: 'POST',
          data: {
			  query: {
				  page: this.page,
				  size: this.pageSize
			  }
          }
        });
        
        if (res.data.length > 0) {
          const newVideos = res.data.map(item => ({
            ...item,
            active: false,
			url: item.video_url
          }));
          
          if (this.page === 1) {
            this.videoList = newVideos;
            this.playCurrentVideo();
          } else {
            this.videoList = [...this.videoList, ...newVideos];
          }
		  uni.setStorageSync("page", this.page);
        }
      } catch (error) {
        console.error('加载失败:', error);
      } finally {
        this.loading = false;
      }
    },
    
    // 加载更多视频
    loadMoreVideos() {
      this.page += 1;
      this.loadVideos();
    },
    
    // 处理滚动事件
    handleScroll(e) {
      if (this.isScrolling) return;
      
      const scrollTop = e.detail.scrollTop;
      const newIndex = Math.round(scrollTop / this.windowHeight);
      
      if (newIndex !== this.currentIndex) {
        this.switchVideo(newIndex);
      }
    },
    
    // 切换视频播放
    switchVideo(newIndex) {
      this.isScrolling = true;
      
      // 暂停旧视频
      if (this.videoContexts[this.currentIndex]) {
        this.videoContexts[this.currentIndex].pause();
      }
      
      // 更新索引并播放新视频
      this.currentIndex = newIndex;
      this.playCurrentVideo();
      
      // 修正滚动位置（解决安卓惯性滚动问题）
      this.scrollTop = newIndex * this.windowHeight;
      
      // 滚动结束解锁
      setTimeout(() => {
        this.isScrolling = false;
      }, 300);
    },
    
    // 播放当前视频
    playCurrentVideo() {
      const videoId = `video-${this.currentIndex}`;
      
      if (!this.videoContexts[this.currentIndex]) {
        this.videoContexts[this.currentIndex] = uni.createVideoContext(videoId, this);
      }
      
      setTimeout(() => {
        this.videoContexts[this.currentIndex].play();
      }, 200);
    },
    
    // 视频播放事件
    onVideoPlay(index) {
      console.log(`视频${index}开始播放`);
    },
    
    // 视频错误处理
    onVideoError(e) {
      console.error('视频播放错误:', e);
      uni.showToast({ title: '视频加载失败', icon: 'none' });
    },
    
    // 点赞处理
    handleLike(item) {
      item.likeCount += item.liked ? -1 : 1;
      item.liked = !item.liked;
    },
    
    // 显示评论
    showComment(item) {
		this.showPopup = true;
      // uni.navigateTo({
      //   url: `/pages/comments/index?id=${item.id}`
      // });
    },
	pageChange(e) {
	  this.page2 = e.value;
	},
	jumpPage() {
		this.page = this.page2;
		this.showPopup = false;
		this.videoList = [];
		this.loadVideos();
	},
	copyAddress() {
		console.log(this.videoList[this.currentIndex].url)
		uni.setClipboardData({
		  data: this.videoList[this.currentIndex].url,
		  success: () => { uni.showToast({ title: '复制成功' }); },
		  fail: (err) => { console.log('复制失败', err); }
		});
		
	}
  }
}
</script>
<style lang="less">
	.video-container {
	  width: 100vw;
	  height: 100vh;
	  background-color: #000;
	  
	  .video-wrapper {
	    width: 100vw;
	    position: relative;
	    
	    .video-item {
	      width: 100%;
	      height: 100%;
	      object-fit: cover;
	      background-color: #000;
	    }
	    
	    .interaction-layer {
	      position: absolute;
	      width: 100%;
	      height: 100%;
	      top: 0;
	      left: 0;
	      z-index: 10;
	      
	      .right-bar {
	        position: absolute;
	        right: 12px;
	        bottom: 80px;
	        display: flex;
	        flex-direction: column;
	        align-items: center;
	        
	        .action-btn {
	          margin-bottom: 20px;
	          text-align: center;
	          
	          image {
	            width: 40px;
	            height: 40px;
	            display: block;
	          }
	          
	          text {
	            color: #fff;
	            font-size: 12px;
	            margin-top: 4px;
	          }
	        }
	      }
	    }
	  }
	  
	  .loading-more {
	    height: 50px;
	    display: flex;
	    justify-content: center;
	    align-items: center;
	    color: #999;
	  }
	}

</style>